package org.jix.weblog.module.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jix.weblog.module.admin.model.vo.tag.*;
import org.jix.weblog.module.admin.service.AdminTagService;
import org.jix.weblog.module.common.domain.dos.ArticleTagRelDO;
import org.jix.weblog.module.common.domain.dos.TagDO;
import org.jix.weblog.module.common.domain.mapper.ArticleTagRelMapper;
import org.jix.weblog.module.common.domain.mapper.TagMapper;
import org.jix.weblog.module.common.enums.ResponseCodeEnum;
import org.jix.weblog.module.common.exception.BizException;
import org.jix.weblog.module.common.model.VO.SelectRspVO;
import org.jix.weblog.module.common.utils.PageResponse;
import org.jix.weblog.module.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author Jix
 * @Date 2024/7/30 9:55
 * @注释
 */

@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;

    /**
     * 添加标签
     * @param addTagReqVO
     * @return
     */
    @Override
    public Response addTag(AddTagReqVO addTagReqVO) {
        // vo 转 do
        List<TagDO> tagDOs = addTagReqVO.getTags().stream()
                .map(tagName -> TagDO.builder()
                        .name(tagName.trim()) // 去掉前后空格
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build())
                .collect(Collectors.toList());
        //批量插入
        try {
            saveBatch(tagDOs);
        } catch (Exception e) {
            log.warn("标签已存在",e);
            throw new BizException(ResponseCodeEnum.TAG_CANT_DUPLICATE);
        }
        return Response.success();
    }

    /**
     * 标签分页查询
     * @param findTagsPageListReqVO
     * @return
     */
    @Override
    public Response findTagsPageList(FindTagsPageListReqVO findTagsPageListReqVO) {
        //分页参数，条件参数
        Long current = findTagsPageListReqVO.getCurrent();
        Long size = findTagsPageListReqVO.getSize();
        String name = findTagsPageListReqVO.getName();
        LocalDate startDate = findTagsPageListReqVO.getStartDate();
        LocalDate endDate = findTagsPageListReqVO.getEndDate();
        //分页查询
        Page<TagDO> page = tagMapper.selectPageList(current, size, name, startDate, endDate);
        List<TagDO> records = page.getRecords();
        //DO转VO
        List<FindTagsPageListRspVO> vos = null;
        if (!CollectionUtils.isEmpty(records)) {
            vos = records.stream().map(
                    tagDO -> FindTagsPageListRspVO.builder()
                            .id(tagDO.getId())
                            .name(tagDO.getName())
                            .createTime(tagDO.getCreateTime())
                            .build()
            ).collect(Collectors.toList());
        }
        return PageResponse.success(page,vos);
    }

    /**
     * 删除标签
     * @param deleteTagVO
     * @return
     */
    @Override
    public Response deleteTag(DeleteTagVO deleteTagVO) {
        //引入标签id
        Long tagId = deleteTagVO.getId();
        // 校验该标签下是否有关联的文章，若有，则不允许删除，提示用户需要先删除标签下的文章
        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(tagId);

        if (Objects.nonNull(articleTagRelDO)) {
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", tagId);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }
        //根据tagId删除
        int count = tagMapper.deleteById(tagId);
        return count == 1?Response.success():Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    /**
     * 标签模糊查询
     * @param searchTagReqVO
     * @return
     */
    @Override
    public Response searchTag(SearchTagReqVO searchTagReqVO) {
        //获取前端传值
        String key = searchTagReqVO.getKey();
        //查询
        List<TagDO> tagDOS = tagMapper.selectByKey(key);
        //DO转VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(vos);
    }

    /**
     * 查询标签select列表数据
     * @return
     */
    @Override
    public Response findTagSelectList() {
        //查询所有标签
        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());
        //DO转VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(vos);
    }
}
